﻿using DotNetStar.TheKing.Infrastructure;
using SDDP;
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DotNetStar.TheKing.Domain
{
    [Table("Attachments")]
    public class Attachment : IEntity<Guid>
    {
        [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; } = Guid.NewGuid();

        /// <summary>
        /// 原文件名
        /// </summary>
        [Required,StringLength(150)]
        public string FileName { get;private set; }
        /// <summary>
        /// 大小，字节
        /// </summary>
        public long Size { get;private set; }
        /// <summary>
        /// 文件的扩展名
        /// </summary>
        [Required,StringLength(8)]
        public string Extension { get;private set; }

        /// <summary>
        /// 随机文件名
        /// </summary>
        [Required, StringLength(128)]
        public string RandomFileName { get; private set; }

        /// <summary>
        /// 存储的相对目录
        /// </summary>
        [Required, StringLength(250)]
        public string RelativePath { get; set; }

        /// <summary>
        /// 相关的Id，由 <see cref="ReferenceType"/> 属性决定。
        /// </summary>
        [Required, StringLength(128)]
        public string ReferenceId { get;private set; }

        /// <summary>
        /// 附件引用类型。
        /// </summary>
        public AttachmentReferenceTypes ReferenceType { get; private set; }

        #region 领域方法

        /// <summary>
        /// 设置文件的信息。
        /// </summary>
        /// <param name="uploadedFile">已上传的文件。</param>
        public void SetFileInfo(FileInfo uploadedFile)
        {
            this.Extension = uploadedFile.Extension;
            this.FileName = Path.GetFileNameWithoutExtension(uploadedFile.Name);
            this.Size = uploadedFile.Length;
            this.RelativePath = uploadedFile.DirectoryName;
            this.RandomFileName = this.FileName.GetHashCode().ToString().MD5();
        }

        /// <summary>
        /// 设置文件的关联
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="referenceId"></param>
        /// <param name="referenceType"></param>
        public void SetReference<T>(T referenceId, AttachmentReferenceTypes referenceType)
        {
            this.ReferenceId = referenceId.ToString();
            this.ReferenceType = referenceType;
        }

        /// <summary>
        /// 获取文件的绝对路径。
        /// </summary>
        /// <returns></returns>
        public string GetFileAbsolutePath() => $"{this.RelativePath}/{this.RandomFileName}{this.Extension}";
        #endregion
    }
}
